package com.yesin.item.service;

import com.yesin.geteway.exception.ExceptionEnum;
import com.yesin.geteway.exception.YsException;
import com.yesin.item.mapper.CategoryMapper;
import com.yesin.item.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 根据父节点id查询商品分类
     * @param pid
     * @return
     */
    public List<Category> queryListByParent(Long pid) {
        Category category = new Category();
        category.setParentId(pid);
        return this.categoryMapper.select(category);
    }

    /**
     * 根据多个id查询多个分类名
     * @param ids
     * @return
     */
    public List<String> queryNamesByIds(List<Long> ids) {
        List<Category> list = this.categoryMapper.selectByIdList(ids);
        List<String> names = new ArrayList<>();
        for(Category category:list){
            names.add(category.getName());
        }
        return names;
    }

    /**
     * 根据品牌id查询商品分类
     * @param bid
     * @return
     */
    public List<Category> queryListBybid(Long bid) {
        Category category = this.categoryMapper.selectCategoryBybid(bid);
        if (category == null){
            throw new YsException(ExceptionEnum.GATEGORY_NOT_FOND);
        }
        List<Category> categories = new ArrayList<>();

        return queryParentsById(category, categories);
    }

    /**
     * 根据分类子节点查询期所有父节点
     * @param category
     * @param categories
     * @return
     */
    public List<Category> queryParentsById(Category category, List<Category> categories){
        if (category.getParentId() != 0) {
            Category parent = this.categoryMapper.selectByPrimaryKey(category.getParentId());
            queryParentsById(parent, categories);
        }
        categories.add(category);
        return categories;
    }

}
